package com.jplus.mvc;

import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;
import com.jplus.core.anno.boot.Component;
import com.jplus.core.mvc.HandlerInterceptorAdapter;
import com.jplus.core.mvc.vo.ModelAndView;
import com.jplus.core.utill.JSON;

/**
 * 请求拦截器
 * 
 * @author Yuanqy
 *
 */
@Component
public class WebInterceptor extends HandlerInterceptorAdapter {
	private final Logger log = LoggerFactory.getLogger(WebInterceptor.class);
	private final ThreadLocal<Long> consumTime = new ThreadLocal<>();

	@PostConstruct
	public void init() {
		/* log.info(">> Init HttpIntercepter ..."); */
	}

	/**
	 * 在preHandle中，可以进行编码、安全控制等处理； 实现预处理
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		log.info("[>> New {} Request URL:{}]", request.getMethod(), request.getRequestURL());
		String params = getParams(request);
		if (!StringUtils.isEmpty(params))
			log.info("[>> Params]:{}", params);
		consumTime.set(System.currentTimeMillis());
		return true;
	}

	/**
	 * 在postHandle中，有机会修改ModelAndView； 后处理（调用了Service并返回ModelAndView，但未进行页面渲染）
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log.debug("[>> 请求成功处理]");
		if (modelAndView != null)
			modelAndView.addObject("v", consumTime.get());
	}

	/**
	 * 在afterCompletion中，可以根据ex是否为null判断是否发生了异常，进行日志记录。 返回处理（已经渲染了页面）
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.info("[>> End {} Request URL:{}]\tTime:{}ms Code:{}\n ", request.getMethod(), request.getRequestURL(),
				(System.currentTimeMillis() - consumTime.get()), response.getStatus());
		consumTime.remove();
		if (ex != null) {
			log.error("ERROR:", ex);
		}
	}

	private String getParams(HttpServletRequest request) {
		Map<String, String[]> maps = request.getParameterMap();
		return JSON.toJSONString(maps);
	}

}
